import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import routers from '@/router'

Vue.use(Vuex)

function localstorageStore(key, value) {
  if (key) {
    if (typeof value === 'object') {
      value = JSON.stringify(value)
    }
    window.localStorage.setItem(key, value)
  }
}

function getlocalstorageStore(key) {
  return window.localStorage.getItem(key)
}

const store = new Vuex.Store({
  state: {
    application: '雨之和管理平台',
    token: '',
    tab: 'home'
  },
  modules: {
    user
  },
  mutations: {
    setToken(state, token) {
      if (token) {
        state.token = token
        saveToken(token)
      }
    },
    setUser(state, user) {
      state.user = user
    }
  },
  actions: {
    setCurrentTab(state, {tab}) {
      if (tab && tab !== 'undefined') {
        this.state.tab = tab
        localstorageStore('currentTab', tab)
      }
    }
  },
  getters: {
    getCurentTab: state => {
      let tab = getlocalstorageStore('currentTab')
      if (!tab) {
        localstorageStore('currentTab', 'home')
        routers.replace('/backend')
      }
      return tab || state.tab
    }
  }
})

export function saveToken(token) {
  localStorage.setItem('accessToken', token)
}

export function getToken() {
  if (!store.state.token) {
    store.commit('setToken', localStorage.getItem('accessToken'))
  }
  return store.state.token
}

export default store
